﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Linq;
using System.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

using CP.Controllers.GPM;
using CP.Entities;
using CP.Utility;
using CP.Win.IViews.GPM;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;
using DevExpress.XtraSplashScreen;


namespace GPM
{
    public partial class FrmWebpartAuth : BaseForm, IWebpartAuthView
    {
        GridCheckMarksSelection selection;
        public int CurrentGroupID { get; private set; }
        public string CurrentGroupName { get; private set; }
        public WebpartAuthController Controller { get; private set; }
        public FrmWebpartAuth()
        {
            InitializeComponent();
            InitializeTreeView();
            this.BarComponents = components;
            this.Controller = new WebpartAuthController(this);
        }

        private void InitializeTreeView()
        {
            DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn1 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
            DevExpress.XtraTreeList.Columns.TreeListColumn treeColMenu = new DevExpress.XtraTreeList.Columns.TreeListColumn();
            treeListColumn1.Caption = "菜单ID";
            treeListColumn1.FieldName = "menu_id";
            treeListColumn1.Name = "treeListColumn1";
            treeColMenu.Caption = "未授权菜单";
            treeColMenu.FieldName = "menu_name";
            treeColMenu.MinWidth = 49;
            treeColMenu.Name = "treeColMenu";
            treeColMenu.OptionsColumn.AllowEdit = false;
            treeColMenu.OptionsColumn.AllowMove = false;
            treeColMenu.OptionsColumn.AllowMoveToCustomizationForm = false;
            treeColMenu.OptionsColumn.ReadOnly = true;
            treeColMenu.OptionsColumn.ShowInCustomizationForm = false;
            treeColMenu.RowFooterSummaryStrFormat = "";
            treeColMenu.SummaryFooter = DevExpress.XtraTreeList.SummaryItemType.Count;
            treeColMenu.SummaryFooterStrFormat = "未授权菜单数：{0}";
            treeColMenu.Visible = true;
            treeColMenu.VisibleIndex = 0;
            treeUnAuth.treeView.Columns.AddRange(new DevExpress.XtraTreeList.Columns.TreeListColumn[] {
            treeListColumn1,
            treeColMenu});

            DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn1Au = new DevExpress.XtraTreeList.Columns.TreeListColumn();
            DevExpress.XtraTreeList.Columns.TreeListColumn treeColMenuAu = new DevExpress.XtraTreeList.Columns.TreeListColumn();
            treeListColumn1Au.Caption = "菜单ID";
            treeListColumn1Au.FieldName = "menu_id";
            treeListColumn1Au.Name = "treeListColumn1";
            treeColMenuAu.Caption = "授权菜单";
            treeColMenuAu.FieldName = "menu_name";
            treeColMenuAu.MinWidth = 49;
            treeColMenuAu.Name = "treeColMenu";
            treeColMenuAu.OptionsColumn.AllowEdit = false;
            treeColMenuAu.OptionsColumn.AllowMove = false;
            treeColMenuAu.OptionsColumn.ReadOnly = true;
            treeColMenuAu.SummaryFooter = DevExpress.XtraTreeList.SummaryItemType.Count;
            treeColMenuAu.SummaryFooterStrFormat = "授权菜单数：{0}";
            treeColMenuAu.Visible = true;
            treeColMenuAu.VisibleIndex = 0;
            treeColMenuAu.OptionsColumn.AllowSize = true;
            treeAuthMenu.treeView.Columns.AddRange(new DevExpress.XtraTreeList.Columns.TreeListColumn[] {
            treeListColumn1Au,
            treeColMenuAu});
        }

        private void FrmWebpartAuth_Load(object sender, EventArgs e)
        {
            selection = new GridCheckMarksSelection(gvUserGroup);
            this.Controller.Initialize();
            this.treeUnAuth.Refresh_ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(treeUnAuth_Refresh_ItemClick);
            this.treeAuthMenu.Refresh_ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(treeAuthMenu_Refresh_ItemClick);
        }

        void treeAuthMenu_Refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            User_Group group = bsUserGroup.Current as User_Group;
            if (null == group)
            {
                XtraMessageBox.Show("提示信息：没有选中角色！");
                return;
            }
            if (null != MenuAuthQuery)
                MenuAuthQuery(group.group_id);
        }

        void treeUnAuth_Refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            User_Group group = bsUserGroup.Current as User_Group;
            if (null == group)
            {
                XtraMessageBox.Show("提示信息：没有选中角色！");
                return;
            }
            if (null != MenuUnAuthQuery)
                MenuUnAuthQuery(group.group_id);
        }

        #region IWebpartAuthView 成员

        public event EventHandler<QueryEventArgs> QuerySubmit;
        public event EventHandler<PositionEventArgs> PositionChanged;
        public event MenuAuthHandler MenuAuth;
        public event MenuUnAuthHandler MenuUnAuth;
        public event MenuUnAuthQueryHandler MenuUnAuthQuery;
        public event MenuAuthQueryHandler MenuAuthQuery;

        public void BindUser_Groups(IList<User_Group> usergroup)
        {
            bsUserGroup.DataSource = usergroup;
        }
        public void BindAuthMenu(IList<CP.Entities.Menu> menus)
        {
            AppendNodes(treeAuthMenu.treeView, menus);
        }
        public void BindUnAuthMenu(IList<CP.Entities.Menu> menus)
        {
            AppendNodes(treeUnAuth.treeView, menus);
        }

        #endregion

        private void bsUserGroup_PositionChanged(object sender, EventArgs e)
        {
           
        }

        private void AppendNodes(TreeList treeview, IList<CP.Entities.Menu> menus)
        {
            Cursor currentCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            treeview.Nodes.Clear();

            var parents = from m in menus
                          where m.parent_id == 0
                          orderby m.sort_order
                          select m;

            treeview.BeginUnboundLoad();
            TreeListNode node;
            foreach (CP.Entities.Menu p in parents)
            {
                node = treeview.AppendNode((new object[] { p.menu_id, p.menu_name }), -1, -1, -1, 3);
                node.Tag = p.menu_id;
                var sons = from m in menus
                           where m.parent_id == p.menu_id
                           orderby m.sort_order
                           select m;
                foreach (CP.Entities.Menu s in sons)
                {
                    TreeListNode child = treeview.AppendNode(new object[] { s.menu_id, s.menu_name }, node.Id, -1, -1, 2);
                    child.Tag = s.menu_id;
                }
            }
            treeview.EndUnboundLoad();

            Cursor.Current = currentCursor;
        }

        private void btnAuth_Click(object sender, EventArgs e)
        { 
            User_Group group = bsUserGroup.Current as User_Group;
            if (null == group)
            {
                XtraMessageBox.Show("提示：没有选中角色！");
                return;
            }

            IList<string> nodes = new List<string>();
            GetCheckedIndeterminateNodes(treeUnAuth.treeView.Nodes, nodes);
            if (0 == nodes.Count)
            {
                XtraMessageBox.Show("提示：没有选中未授权的菜单！");
                return;
            }

            if (null == MenuAuth)
            {
                XtraMessageBox.Show("提示：后台服务没有注册，请联系开发人员！");
                return;
            }

            try
            {
                //SplashScreenManager.ShowForm(typeof(WaitForm1));
                splashScreenManager1.ShowWaitForm();
                MenuAuth(group.group_id, nodes);
                LogHelper.Log("角色授权", "insert", "授权", "group_id:" + group.group_id, "nodes:" + string.Join(",", nodes));
                XtraMessageBox.Show("提示：菜单授权成功！");
                PositionChanged(this.gvUserGroup,
                    new PositionEventArgs((bsUserGroup.Current as User_Group).group_id));
            }
            catch (Exception ex)
            { 
                XtraMessageBox.Show(ex.Message);
            }
            //SplashScreenManager.CloseForm();
            splashScreenManager1.CloseWaitForm();
        }

        private void GetCheckedIndeterminateNodes(TreeListNodes nodes, IList<string> checkednodes)
        {
            foreach (TreeListNode node in nodes)
            {
                if ((node.CheckState == CheckState.Checked) ||
                    (node.CheckState == CheckState.Indeterminate))
                {
                    checkednodes.Add(node.Tag.ToString());
                    GetCheckedIndeterminateNodes(node.Nodes, checkednodes);
                }
            }
        }

        private void GetCheckedNodes(TreeListNodes nodes, IList<string> checkednodes)
        {
            foreach (TreeListNode node in nodes)
            {
                if (node.CheckState == CheckState.Checked)
                {
                    checkednodes.Add(node.Tag.ToString());
                    GetCheckedNodes(node.Nodes, checkednodes);
                }
                if (node.CheckState == CheckState.Indeterminate)
                {
                    GetCheckedNodes(node.Nodes, checkednodes);
                }
            }
        }

        private void btnCancelAuth_Click(object sender, EventArgs e)
        {
            User_Group group = bsUserGroup.Current as User_Group;
            if (null == group)
            {
                XtraMessageBox.Show("提示：没有选中角色！");
                return;
            }

            IList<string> nodes = new List<string>();
            GetCheckedNodes(treeAuthMenu.treeView.Nodes, nodes);
            if (0 == nodes.Count)
            {
                XtraMessageBox.Show("提示：没有选中授权的菜单！");
                return;
            }

            if (null == MenuUnAuth)
            {
                XtraMessageBox.Show("提示：后台服务没有注册，请联系开发人员！");
                return;
            }

            try
            {
                splashScreenManager1.ShowWaitForm();
                //SplashScreenManager.ShowForm(typeof(WaitForm1));
                MenuUnAuth(group.group_id, nodes);
                LogHelper.Log("角色授权", "delete", "取消授权", "group_id:" + group.group_id, "nodes:" + string.Join(",", nodes));
                XtraMessageBox.Show("提示：菜单取消授权成功！");
                PositionChanged(this.gvUserGroup,
                    new PositionEventArgs((bsUserGroup.Current as User_Group).group_id));
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
            //SplashScreenManager.CloseForm();
            splashScreenManager1.CloseWaitForm();
        }

        private void barGroupRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (null != QuerySubmit)
                QuerySubmit(sender, new QueryEventArgs(null));
        }

        private void gvUserGroup_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            //SplashScreenManager.ShowForm(typeof(WaitForm1));
            splashScreenManager1.ShowWaitForm();
            User_Group group = gvUserGroup.GetFocusedRow() as User_Group;
            if (null == group)
                return;
            this.CurrentGroupID = group.group_id;
            this.CurrentGroupName = group.group_name;
            PositionEventArgs args = new PositionEventArgs(group.group_id);
            if (null != PositionChanged)
                PositionChanged(sender, args);
            //SplashScreenManager.CloseForm();
            splashScreenManager1.CloseWaitForm();
        }


    }
}